package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.protocol.ResponseServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-11-11
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    /**
     * 分页查询文章内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listCondition(WmNewsPageDto dto) {
        //判断用户是否登录
        User user = MediaThreadLocalUtil.get();
        if (StringUtils.isEmpty(user)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        //只能查看自己得文章
        query.eq(WmNews::getUserId, user.getUserId());
        //按照发布文章先后排序
        query.orderByDesc(WmNews::getPublishTime);
        //状态不为空
        if (dto.getStatus() != null) {
            query.eq(WmNews::getStatus, dto.getStatus());
        }
        //关键字不为空,添加关键字根据文章标题模糊查询
        if (dto.getKeyword() != null) {
            query.like(WmNews::getTitle, dto.getKeyword());
        }
        //频道id不为空
        if (dto.getChannelId() != null) {
            query.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //开始时间不为空
        if (dto.getBeginPubDate() != null) {
            query.eq(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        //结束时间不为空
        if (dto.getEndPubDate() != null) {
            query.eq(WmNews::getPublishTime, dto.getEndPubDate());
        }
        //分页
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> iPage = this.page(page, query);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
        return result;
    }

    @Autowired
    @Lazy //懒加载--> 保险起见,加这个注解以防出现异常
    private IAuditService iAuditService;
    /**
     * 保存/发布/修改文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //获取登录用户
        //发布文章需要登陆
        User user = MediaThreadLocalUtil.get();
        if (StringUtils.isEmpty(user)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //如果dto中有id,则说明需要更新
        if(dto.getId()!=null){
            //需要删除关联,根据id删除
            removeRelation(dto.getId());
        }
        //构建文章wmnews,并保存到数据库
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(true);
        //将图片转成json数据保存
        String image = JSON.toJSONString(dto.getImages());
        wmNews.setImages(image);
        //提取图片
        List<ImageDto> imagesContent = getImagesContent(dto.getContent());
        //如过前端传来得数据为-1,自动,把内容图片转为封面图片
        if(dto.getType()==-1){
            //如果为0,无图则无需添加封面
            if(imagesContent.size()<=0){
                wmNews.setType(0);
            }else if(imagesContent.size()<3){
                //如果为1,单图图则需从内容图片添加封面
                wmNews.setType(1);
                wmNews.setImages(JSON.toJSONString(imagesContent.subList(0,1)));
            }else {
                //如果为3,多图图则需从内容图片添加封面
                wmNews.setType(3);
                wmNews.setImages(JSON.toJSONString(imagesContent.subList(0,3)));
            }
        }
        this.saveOrUpdate(wmNews);
        if(dto.getStatus()!=0) {
            //保存封面和文章得关系
            List<ImageDto> imageDtos = JSON.parseArray(wmNews.getImages(), ImageDto.class);
            saveRelation(imageDtos, wmNews, 1);
            //保存内容图片和文章得关系
            saveRelation(imagesContent, wmNews, 0);
            //开启自动审核流程
            iAuditService.audit(wmNews);
        }
        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Value("${topic.enableTopic}")
    private String enableTopic;

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult enable(WmNewsDto dto) {
        //根据id查询文章
        WmNews wmNews = this.getById(dto.getId());
        //判断文章是否存在
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断文章是否上架
        if(wmNews.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 修改文章,修改上下架状态
        wmNews.setEnable(dto.getEnable()==1 ? true :false);
        this.updateById(wmNews);
        //
        String key=""+wmNews.getArticleId();
        String value=dto.getEnable()==1?"true":"false";
        kafkaTemplate.send(enableTopic, key, value);
        return ResponseResult.okResult();
    }

    /**
     * 根据id删除关联得文章内容等
     * @param newId
     */
    private void removeRelation(Integer newId) {
        LambdaQueryWrapper<WmNewsMaterial> query=new LambdaQueryWrapper<>();
        query.eq(WmNewsMaterial::getNewsId,newId);
        iWmNewsMaterialService.remove(query);
    }

    /**
     * 内容图片和文章,提取图片
     *
     * @param content
     * @return
     */
    private List<ImageDto> getImagesContent(String content) {
        List<ImageDto> imageDtoList=new ArrayList<>();
        //将json转成数据对象集合
        List<ContentDto> dtoList = JSON.parseArray(content, ContentDto.class);
        //遍历
        for (ContentDto contentDto : dtoList) {
            //判断类型是否为图片image
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imageDtoList.add(imageDto);
            }
        }
        return imageDtoList;
    }

    @Autowired
    private IWmNewsMaterialService iWmNewsMaterialService;

    /**
     * 保存图片和文章得关系
     *
     * @param images
     * @param wmNews
     * @param type
     */
    private void saveRelation(List<ImageDto> images, WmNews wmNews, int type) {
        //定义排序 为0
        int ord = 0;
        //对素材进行遍历
        for (ImageDto image : images) {
            // 构建文章和图片
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(image.getId());
            wmNewsMaterial.setNewsId(wmNews.getId());
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd(ord);
            ord++;
            //保存
            iWmNewsMaterialService.save(wmNewsMaterial);
        }
    }
}
